using UnityEngine;
using System;
using System.Collections.Generic;
using TMPro;

public class WinBarSystem : MonoBehaviour
{
    [SerializeField] private Bag bag;
    [SerializeField] private Button3D button3D;
    [SerializeField] private TMP_Text tmp;

    public List<BagItemData> dataList { get; private set; } = new List<BagItemData>();
    public List<IBagItemView> viewList { get; private set; } = new List<IBagItemView>();
    public IBagItemView selectedView { get; set; }

    // 新增关闭事件
    public event Action<WinBarSystem> OnClosed;

    /// <summary>
    /// Bag 选中后的 Reaction（POST）
    /// </summary>
    private void BagSelectedPostReaction(BagSelectedGA bagSelectedGA)
    {
        if (viewList.Contains(bagSelectedGA.View))
        {
            foreach (var view in viewList)
                view.IsHighlighted = false;

            bagSelectedGA.View.IsHighlighted = true;
            selectedView = bagSelectedGA.View;

            if (selectedView is RelicView rv)
                InfoSystem.Instance.hero.Relics.Add(rv.relic);
            else if (selectedView is CardView cv)
                InfoSystem.Instance.hero.Cards.Add(cv.card);

            OnClose();
        }
    }

    /// <summary>
    /// 初始化 WinBar 数据
    /// </summary>
    public void Setup(List<BagItemData> datas)
    {
        dataList = datas;
        InitBag();
        viewList = bag.GetViews();
        InitButton();
        ActionSystem.SubscribeReaction<BagSelectedGA>(BagSelectedPostReaction, ReactionTiming.POST);
    }

    private void InitBag()
    {
        bag.Setup(dataList);
    }

    private void InitButton()
    {
        if (dataList.Count == 0) return;

        if (dataList[0] is Card)
            tmp.text = "卡牌奖励";
        else if (dataList[0] is Relic)
            tmp.text = "遗物奖励";
    }

    public void OnOpenBag()
    {
        bag.gameObject.SetActive(true);
    }

    /// <summary>
    /// 关闭 WinBar 并通知外部
    /// </summary>
    public void OnClose()
    {
        ActionSystem.UnsubscribeReaction<BagSelectedGA>(BagSelectedPostReaction, ReactionTiming.POST);

        OnClosed?.Invoke(this); // 通知 WinView

        Destroy(this.gameObject);
    }

    public void OnBack()
    {
        bag.gameObject.SetActive(false);
    }
}
